package xyz.fivefaith.tool.boot.util;

import xyz.fivefaith.tool.common.excetion.UtilException;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.BiConsumer;

/**
 * 线程池工具类
 *
 * @author zhaoanchi
 * @version 1.0
 * @since 1.0
 */
public class ExecutorUtil {

    private static final Executor EXECUTOR = SpringUtil.getBean(Executor.class);

    /* ******************** 异步任务 ******************** */

    /**
     * 异步方法
     *
     * @param runnable 回调方法
     */
    public static void execute(Runnable runnable) {
        try {
            EXECUTOR.execute(runnable);
        } catch (Exception e) {
            throw new UtilException(e);
        }
    }

    /**
     * 异步方法
     *
     * @param param1 参数1
     * @param param2 参数2
     * @param consumer 回调方法
     * @param <P1> 参数类型1
     * @param <P2> 参数类型2
     */
    public static <P1, P2> void execute(P1 param1, P2 param2, BiConsumer<P1, P2> consumer) {
        try {
            Runnable runnable = () -> consumer.accept(param1, param2);
            EXECUTOR.execute(runnable);
        } catch (Exception e) {
            throw new UtilException(e);
        }
    }

    /**
     * 执行任务
     *
     * @param executorService ExecutorService
     * @param callable 回调
     * @param <T> 返回的结果集Future泛型
     * @return Future泛型
     */
    public static <T> Future<T> submit(ExecutorService executorService, Callable<T> callable) {
        return executorService.submit(callable);
    }
}
